package blog.controller;

import blog.entity.BatchResult;
import blog.entity.QueryJson;
import blog.entity.ResultJson;
import blog.pojo.NoticeCategory;
import blog.service.NoticeCategoryService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/api/noticeCategory")
public class NoticeCategoryController {

    @Autowired
    private NoticeCategoryService service;

    @RequestMapping("/findPage")
    public ResultJson findPage(@RequestBody QueryJson<NoticeCategory> queryJson) throws Exception{
        if(queryJson.getPage() == null) return ResultJson.ARGUMENT_NULL;


        IPage<NoticeCategory> page = service.getPage(queryJson.getPage(), queryJson.getEntity(), queryJson.getKeywords());
        return ResultJson.isSuccess(page);
    }

    @RequestMapping("/edit")
    public ResultJson edit(@RequestBody QueryJson<NoticeCategory> queryJson) throws Exception{
        if(queryJson.getEntity() == null) return ResultJson.ARGUMENT_NULL;

        if(queryJson.getEntity().getId() == null){
            if(!service.insert(queryJson.getEntity())){
                return ResultJson.INSERT_ERROR;
            }
        } else {
            if(!service.update(queryJson.getEntity())){
                return ResultJson.UPDATE_ERROR;
            }
        }
        return ResultJson.SUCCESS;
    }

    @RequestMapping("/updateManyByIds")
    public ResultJson updateManyByIds(@RequestBody QueryJson<NoticeCategory> queryJson) throws Exception{
        if(queryJson.getEntity() == null || queryJson.getIds() == null){
            return ResultJson.ARGUMENT_NULL;
        }
        int success = 0, fail = 0;
        for(Integer id : queryJson.getIds()){
            NoticeCategory noticeCategory = queryJson.getEntity().setId(id);
            if (service.update(noticeCategory)) {
                success++;
            } else {
                fail++;
            }
        }
        return ResultJson.isSuccess(BatchResult.SET(success,fail));
    }

    @RequestMapping("/find")
    public ResultJson find(@RequestBody QueryJson<NoticeCategory> queryJson) throws Exception{
        if(queryJson.getEntity() == null) {
            return ResultJson.ARGUMENT_NULL;
        }
        return ResultJson.isSuccess(service.get(queryJson.getEntity()));
    }
    @RequestMapping("findAll")
    public ResultJson findAll() throws Exception{
        return ResultJson.isSuccess(service.getAll());
    }

}
